package com.chinatgl.latte.ec.main.cart;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chinatgl.latte.delegates.LatteDelegate;
import com.chinatgl.latte.ec.R;
import com.chinatgl.latte.ec.adapter.ShopCartAdapter;
import com.chinatgl.latte.ec.mode.Cart;
import com.chinatgl.latte.util.DecimalUtil;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import me.yokeyword.fragmentation.ISupportFragment;


/**
 * 文件描述: 购物车有内容显示的界面
 * 作者: Created by 杨伟乔 on 2017/8/11 0011.
 * 版本号: 1.0
 */

@SuppressLint("ValidFragment")
public class NoEmptyCartDelegate extends LatteDelegate {
    private TextView tvShopCartSubmit, tvShopCartSelect, tvShopCartTotalNum;


    private RecyclerView rlvShopCart, rlvHotProducts;
    private ShopCartAdapter mShopCartAdapter;
    private LinearLayout llPay;
    private RelativeLayout rlHaveProduct;
    private static List<Cart.ListBean> mAllOrderList = new ArrayList<>();


    private ArrayList<Cart.ListBean> mGoPayList = new ArrayList<>();
    private List<String> mHotProductsList = new ArrayList<>();
    private TextView tvShopCartTotalPrice;
    private int mCount, mPosition;
    private double mTotalPrice1;
    private boolean mSelect;
    private LinearLayout llHaveProduct;

    @SuppressLint("ValidFragment")
    private NoEmptyCartDelegate(List<Cart> result) {
        mAllOrderList.clear();
        for (Cart cart : result) {
            mAllOrderList.addAll(cart.getList());
        }
        isSelectFirst(mAllOrderList);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_cart_no_empty;
    }
    public static void isSelectFirst(List<Cart.ListBean> list) {
        if (list.size() > 0) {
            list.get(0).setIsFirst(1);
            for (int i = 1; i < list.size(); i++) {
                //判断商品是不是和上一个商品是属于同一家店铺的
                if (list.get(i).getShopId() == list.get(i - 1).getShopId()) {
                    list.get(i).setIsFirst(2);
                } else {
                    list.get(i).setIsFirst(1);
                }
            }

        }

    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        //实现全选和反选的按钮
        tvShopCartSelect = (TextView) rootView.findViewById(R.id.tv_shopcart_addselect);
        //显示总价
        tvShopCartTotalPrice = (TextView) rootView.findViewById(R.id.tv_shopcart_totalprice);
        //显示商品的种类数量
        tvShopCartTotalNum = (TextView) rootView.findViewById(R.id.tv_shopcart_totalnum);
        //最外层的相对布局 找出来没什么用
        rlHaveProduct = (RelativeLayout) rootView.findViewById(R.id.rl_shopcart_have);

        //显示商品列表的主要控件 recycleView
        rlvShopCart = (RecyclerView) rootView.findViewById(R.id.rlv_shopcart);

        //最下面的支付的线性布局
        llPay = (LinearLayout) rootView.findViewById(R.id.ll_pay);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        llPay.setLayoutParams(lp);
//提交商品的控件  去结算
        tvShopCartSubmit = (TextView) rootView.findViewById(R.id.tv_shopcart_submit);
        rlvShopCart.setLayoutManager(new LinearLayoutManager(getActivity()));
        //设置商品的列表的适配器
        mShopCartAdapter = new ShopCartAdapter(getActivity(), mAllOrderList);

        rlvShopCart.setAdapter(mShopCartAdapter);

        //删除商品接口
        mShopCartAdapter.setOnDeleteClickListener(new ShopCartAdapter.OnDeleteClickListener() {
            @Override
            public void onDeleteClick(View view, final int position, String cartid) {
                //在适配器里面去判断删除成功后再刷新适配器
//                ArrayMap<String, String> map = new ArrayMap<>();
//                map.put("memberId", MyApp.getUser().getId());
//                map.put("cartItemId", cartid);
//                Type type = new TypeToken<Result>() {
//                }.getType();
//                NetRequest.postForparams(Api.CARTDEL, map, HTTP_TASK_KEY, type, new onNetRquestListener() {
//                    @Override
//                    public void requestdataFinish(String catalog, Object bean) {
//
//                        if (bean instanceof String) {
//                            return;
//                        }
//                        //判断是否成功
//                        Result bean1 = (Result) bean;
//
//                        if (bean1.getCode() == 0) {
//                            mAllOrderList.remove(position);
//                            //重新排序，标记所有商品不同商铺第一个的商品位置
//                            CartFragment.isSelectFirst(mAllOrderList);
////                            if (checkDatas(mAllOrderList)) {
//                            //刷新适配器
//                            mShopCartAdapter.notifyDataSetChanged();
//                            if (mAllOrderList.size() == 0) {
//                                // TODO: 2017/07/18 显示空的购物车
//                                //显示空的界面
//                                llCartEmpty.setVisibility(View.VISIBLE);
//                                llGotoLogin.setVisibility(View.GONE);
//                                rlHaveProduct.setVisibility(View.GONE);
//                                //加载推荐的数据
//                                getRecommendDatas();
//
//                            }
//
//
////                            }
//                        }
//                    }
//
//                    @Override
//                    public void requestdataFailed(String msg, Exception e) {
//
//                        Toastutils.showToastCenter("删除失败!");
//                    }
//                }, getActivity(), CacheMode.NO_CACHE);


            }
        });
        //修改数量接口
        mShopCartAdapter.setOnEditClickListener(new ShopCartAdapter.OnEditClickListener() {
            @Override
            public void onEditClick(final int position, String cartid, final int count) {
//
//                ArrayMap<String, String> map = new ArrayMap<>();
//                map.put("memberId", MyApp.getUser().getId());
//                map.put("cartItemId", cartid);//cartItemId
//                map.put("num", String.valueOf(count));
//
//                Type type = new TypeToken<Result>() {
//                }.getType();
//                NetRequest.postForparams(Api.CARTEDIT, map, HTTP_TASK_KEY, type, new onNetRquestListener() {
//                    @Override
//                    public void requestdataFinish(String catalog, Object bean) {
//
//                        if (bean instanceof String) {
//                            return;
//                        }
//                        Result result = (Result) bean;
//
//                        if (result.getCode() == 0) {
//                            //修改的商品的id
//                            //修改后的数量
//                            mCount = count;
//                            //修改的位置
//                            mPosition = position;
//                            mAllOrderList.get(position).setNum(count);
//                            //   if (checkDatas(mAllOrderList)) {
//                            //刷新适配器
//                            mShopCartAdapter.notifyDataSetChanged();
//                            //  }
//                        } else {
//                            Toastutils.showToastCenter(result.getMessage());
//                        }
//                    }
//
//                    @Override
//                    public void requestdataFailed(String msg, Exception e) {
//                        Toastutils.showToastCenter(msg);
//                    }
//                }, getActivity(), CacheMode.NO_CACHE);


            }
        });
        //实时监控全选按钮
        mShopCartAdapter.setResfreshListener(new ShopCartAdapter.OnResfreshListener() {
            @Override
            public void onResfresh(boolean isSelect) {
                mSelect = isSelect;
                if (isSelect) {
                    Drawable left = getResources().getDrawable(R.drawable.shopcart_selected);
                    tvShopCartSelect.setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);
                } else {
                    Drawable left = getResources().getDrawable(R.drawable.shopcart_unselected);
                    tvShopCartSelect.setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);
                }
                //初始化总价是 0
                float mTotalPrice = 0;
                //初始化数量是0
                int mTotalNum = 0;
                //初始化返利的j金额
                String mTotalFanli = "0";
                //付款的总价
                mTotalPrice1 = 0;
                //现在要去付款的集合清 0
                mGoPayList.clear();
                //便利现在的集合
                for (int i = 0; i < mAllOrderList.size(); i++)
                    //如果现在的商品是被选择的 获取现在商品的价格和数量
                    if (mAllOrderList.get(i).isSelect()) {
                        //计算价格
                        mTotalPrice += (mAllOrderList.get(i).getNowPrice()) * mAllOrderList.get(i).getNum();
                        //计算数量
                        mTotalNum += mAllOrderList.get(i).getNum();

                        mTotalFanli = DecimalUtil.add(mTotalFanli, DecimalUtil.multiply(mAllOrderList.get(i).getRebate(), String.valueOf(mAllOrderList.get(i).getNum())));
                        //添加到付款商品的集合中
                        mGoPayList.add(mAllOrderList.get(i));
                    }

                mTotalPrice1 = mTotalPrice;
                //这里显示的总价会有异常  2.339999999 需要格式化 保留小数点的后两位数
                DecimalFormat df = new DecimalFormat("0.00");
                //总价显示的时候格式化
                tvShopCartTotalPrice.setText("总价：" + df.format(mTotalPrice1));
                tvShopCartTotalNum.setText("返利" + mTotalFanli + "元");
            }
        });

        //全选 全选和反选
        tvShopCartSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置状态是相反的
                mSelect = !mSelect;
                if (mSelect) { //如果是全选
                    //设置左侧的图片为全选的图片
                    Drawable left = getResources().getDrawable(R.drawable.shopcart_selected);

                    tvShopCartSelect.setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);
                    //遍历集合 设置状态为相反的
                    for (int i = 0; i < mAllOrderList.size(); i++) {
                        mAllOrderList.get(i).setSelect(true);
                        mAllOrderList.get(i).setShopSelect(true);
                    }
                } else {//如果是反选
                    Drawable left = getResources().getDrawable(R.drawable.shopcart_unselected);
                    tvShopCartSelect.setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);
                    for (int i = 0; i < mAllOrderList.size(); i++) {
                        mAllOrderList.get(i).setSelect(false);
                        mAllOrderList.get(i).setShopSelect(false);
                    }
                }
                // if (checkDatas(mAllOrderList)) {
                //刷新适配器
                mShopCartAdapter.notifyDataSetChanged();
                // }

            }
        });
        tvShopCartSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                StringBuilder sb = new StringBuilder();

                if (mGoPayList != null && mGoPayList.size() > 0) {
                    for (int i = 0; i < mGoPayList.size(); i++) {
                        String cartItemId = mGoPayList.get(i).getCartItemId();
                        if (i == mGoPayList.size() - 1) {

                            sb.append(cartItemId);
                        } else {

                            sb.append(cartItemId + ",");
                        }

                    }

                }


                //购物车结算 POST /mobi/order/settlement
//                ArrayMap<String, String> map = new ArrayMap<>();
//                map.put("memberId", MyApp.getUser().getId());
//                map.put("cartIds", sb.toString());
//                Type type = new TypeToken<Result<Order>>() {
//                }.getType();
//                NetRequest.postForparams(Api.SETTLEMENT, map, HTTP_TASK_KEY, type, new onNetRquestListener() {
//                    @Override
//                    public void requestdataFinish(String catalog, Object bean) {
//
//
///****
// *
// * {"address":{"id":"1","name":"测试收货人","mobi":"18768124367","location":"浙江杭州滨江","address":"云厦连园10栋1单元601"},"orders":[{"orderItems":"[{\"fee\":\"0.10\",\"num\":1,\"price\":\"0.10\",\"productId\":1,\"productName\":\"商品名称\",\"productSkuId\":1,\"productSpec\":\"黑色、大号\",\"skuId\":1,\"skuImage\":\"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png\",\"totalFee\":\"0.10\"},{\"fee\":\"0.52\",\"num\":4,\"price\":\"0.13\",\"productId\":1,\"productName\":\"商品名称\",\"productSkuId\":4,\"productSpec\":\"白色、小号\",\"skuId\":4,\"skuImage\":\"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png\",\"totalFee\":\"0.52\"},{\"fee\":\"0.36\",\"num\":3,\"price\":\"0.12\",\"productId\":1,\"productName\":\"商品名称\",\"productSkuId\":3,\"productSpec\":\"黑色、小号\",\"skuId\":3,\"skuImage\":\"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png\",\"totalFee\":\"0.36\"}]","totalNum":8,"totalAmount":"0.98","shopId":"1","shopName":"测试店铺","expressFee":"0.00"}],"totalAmount":"0.98","totalNum":8}
// *
// */
//                        if (bean != null) {
//                            if (bean instanceof String) {
//                                Toastutils.showToastCenter("订单提交失败");
//                            }
//                            Result<Order> bean1 = (Result) bean;
//                            if (bean1.getCode() == 0) {
//                                //下单成功 跳转到订单的界面
//
//                                Order result = bean1.getResult();
//                                if (result != null) {
//                                    Intent intent = new Intent(getActivity(), SubmitOrderActivity.class);
//                                    intent.putExtra(Contains.ORDER, bean1.getResult());
//                                    startActivity(intent);
//                                } else {
//                                    Toastutils.showToastCenter("订单提交失败");
//                                }
//
//
//                            }
//                        }
//
//                    }
//
//                    @Override
//                    public void requestdataFailed(String msg, Exception e) {
//
//                    }
//                }, getActivity(), CacheMode.NO_CACHE);

            }
        });

    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);


    }

    public static NoEmptyCartDelegate create(List<Cart> result) {

        return new NoEmptyCartDelegate(result);
    }
}
